#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "lm_net.h"
#include "lm_net_base.h"
#include "lm_comman.h"

#define MAXCLIENTNUM 1000

#define DEFAULT_RECV_BUFFER_SIZE 128072
#define MAX_RECV_BUFFER_SIZE 262144


lmNet::lmNet(char* ip, ushort p, char t)
{
	fs = NULL;
	sk = new sock_t();
	memcpy(sk->ip, ip,  sizeof(sk->ip));
	sk->port   = p;
	sk->nety   = t;
	sk->id     = 1;
	sk->addLen = sizeof(struct sockaddr_in);
}


lmNet::~lmNet()
{
	if(fs){	
		FREE_OBJAARY(fs->start);
		FREE_OBJ(fs);
	}

	FREE_OBJ(sk);
}

int lmNet::nsend(string data)
{
	return _send(data.c_str(), data.size(), sk);
}

int lmNet::nsend(char *data, int len)
{
	int ret = _send(data, len, sk);
	if (ret <= 0) {
		LOGA("ret:%d, send error:%s\n", ret, strerror(errno));
	}

	return ret;
}

int lmNet::nsendByIovec(struct iovec *iov, uint iovSize)
{
	return sendIov(iov, iovSize, sk);
}

uchar lmNet::get_net_type()
{
	return sk->nety;
}

sock_t* lmNet::get_sock()
{
	return sk;
}

int lmNet::create_server()
{
	//create sock.	
	create_servere_socket(sk);
	set_sock_attr(sk->sock);

	PRT_INF("create socket {type:%d, socket:%d, port:%d}.", sk->nety, sk->sock, sk->port);
		
	//bind sock.
	if(::bind(sk->sock, (struct sockaddr *)&sk->sadd, sk->addLen) < 0)
	{
		PRT_INF("bind failed.");
		perror("error");
		::close(sk->sock);
		return -1;
	}

	DO_CONDX(sk->nety == TP_TCP, ::listen(sk->sock, MAXCLIENTNUM));
	

	return  0;
}

int lmNet::create_client()
{
	if(create_client_socket(sk) < 0){
		LOGE("Creta client failed.\n");
		return -1;
	}
	
	set_block(1, sk->sock);
	set_sock_attr(sk->sock);

	PRT_INF("create client socket {type:%d, socket:%d, port:%d}.", sk->nety, sk->sock, sk->port);
	
	return 0;
}

